<?php

namespace Action\User\Picture;

class Save extends \Library\Action\UserAction 
	implements \Library\Action\AjaxAction {
	
	public function execute() {
		parent::execute();
		
		$user = _u();
		$image = $this->getParam( 'image' );
		$left = (int) $this->getParam( 'left' );
		$top = (int) $this->getParam( 'top' );
		$width = (int) $this->getParam( 'width' );
		
		_a( $left >= 0 && $top >= 0 && $width >= 50, 'Invalid dimensions' );

		_a( preg_match( '/^[^\/]+$/', $image ), 'Invalid image' );
		
		$conf = \Library\Config::get( 'path' );
		$image =  $conf['public'] . '/' . $conf['images']['tmp'] . '/' . $image;
		
		_a( file_exists( $image ), 'File not found : ' . $image );
		
		$content = file_get_contents( $image );

		$picture = new \Library\Picture( $content );
		$path = $picture->save( $left, $top, $width );
		
		$user->setPicture( $path );
		
		\Library\Auth\Session::getSession()->setUser( $user );
		
		return true;
	}
}
